package com.letv.work.special;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.letv.bean.SummaryBean;
import com.letv.common.ConnectionManager;
import com.letv.common.Constants;
import com.letv.common.Mappings;
import com.letv.conf.ConfigFactory;
import com.letv.dataprocess.DataprocessServiceImpl;
import com.letv.download.DownloadServiceImpl;
import com.letv.mms.cache.factory.CacheFactory;
import com.letv.util.SQLUtil;
import com.letv.work.AbstarctWorkJob;

public class SpecialJob extends AbstarctWorkJob {

	private static String cbasekeyprefix = ConfigFactory.getString("cbaseprefix.name");
	private static final Logger log = LoggerFactory.getLogger(SpecialJob.class);

	@Override
	public SummaryBean work(String type) {
		 return readIncFromFile();
	}
	
	public SummaryBean readIncFromFile() {
		cmsimg();
		
		SummaryBean bean = new SummaryBean();
		String fileName = ConfigFactory.getString("index.incremental.localupdatefile");
		File file = new File(Constants.WEB_PATH+fileName);
		if (!file.exists()) {
			log.info("localupdatefile not exist, do nothing");
			return bean;
		}

		if (Mappings.DICTIONARY_MAP == null || Mappings.DICTIONARY_MAP.size() == 0) {
			ConnectionManager cm = null;
			Connection connToSrc = null;
			Connection connToLeso = null;
			try {
				cm = ConnectionManager.getInstance();
				connToSrc = cm.getConnectionFromMMS();
				SQLUtil.setDictionary(connToSrc);
				SQLUtil.setStar(connToSrc);
				SQLUtil.setRAlbumMap(connToSrc);
				SQLUtil.setCagegoryMapping(connToLeso);
			} catch (Exception e) {
				log.error("init dictionary and star map error!", e);
				bean.setErrorMsg("init dictionary and star map error!");
				return bean;
			} finally {
			    SQLUtil.close(connToSrc);
			    SQLUtil.close(connToLeso);
			}
		}

		ArrayList<Map<String, Object>> records = new ArrayList<Map<String, Object>>();
		try {
			FileReader fr = new FileReader(fileName);
			BufferedReader bufferedreader = new BufferedReader(fr);
			String instring;
			while ((instring = bufferedreader.readLine()) != null) {
				if (0 != instring.length()) {
					String[] strarray = instring.split(":");
					if (strarray.length != 3) {
						log.error("format error in localupdatefile!, data:" + instring);
						continue;
					}
					HashMap<String, Object> record = new HashMap<String, Object>();
					record.put("type", strarray[0]);
					record.put("action", strarray[1]);
					record.put("itemId", strarray[2]);
					records.add(record);
				}
			}
			fr.close();
		} catch (FileNotFoundException e) {
			log.info("localupdatefile not exist, do nothing", e);
			bean.setErrorMsg("localupdatefile not exist, do nothing!");
			return bean;
		} catch (Exception e) {
			log.error("read localupdatefile error!", e);
			bean.setErrorMsg("read localupdatefile error!");
			file.renameTo(new File(fileName + ".bak"));
			return bean;
		}

		// 文件中有内容，则更新
		if (records.size() != 0) {
			log.info("行数" + records.size());

			DownloadServiceImpl dsi = new DownloadServiceImpl();
			DataprocessServiceImpl dps = new DataprocessServiceImpl();

			boolean incrementalResult = false;

			try {
				String action = "";
				String type = "";
				String itemId = "";

				for (Map<String, Object> msg : records) {
					action = String.valueOf(msg.get("action"));
					type = String.valueOf(msg.get("type"));
					itemId = String.valueOf(msg.get("itemId"));

					log.info("get msg from localupdatefile:action=" + action + " type=" + type
					        + " itemId=" + itemId);

					if (Constants.INDEX_LESO_EXTRAET.equals(type)) {
						incrementalResult = dps.processLesoExtraetById(Integer.parseInt(itemId),
						        action);
					} else {
						if (Constants.MQ_ACTION_DEL.equals(action)) {
							log.debug("del");
							incrementalResult = incrementalDelete(dsi, dps, action, type, itemId);
						} else if (Constants.MQ_ACTION_ADD.equals(action)) {
							log.debug("add");
							incrementalResult = incrementalDown(dsi, dps, action, type, itemId);
						} else if (Constants.MQ_ACTION_MOD.equals(action)) {
							log.debug("mod");
							incrementalResult = incrementalUpdate(dsi, dps, action, type, itemId);
						} else {
							log.debug("else");
							incrementalResult = false;
						}
					}

				}
			} catch (Exception e) {
				log.error("incremental localupdatefile operation error!", e);
				bean.setErrorMsg("incremental localupdatefile operation error!");
			}
			file.renameTo(new File(fileName + ".bak"));
		} else {
			log.info("行数为0,本次不执行");
		}

		log.info("process localupdatefile success");

		return bean;
	}
	
	private boolean incrementalDown(DownloadServiceImpl dsi, DataprocessServiceImpl dps,
	        String action, String type, String id) {
		try {
		    Long lid = Long.valueOf(id);
			if (dsi.downDataById(type, lid)) {
				if (dps.processDataById(type, lid)) {
					log.info("down type=index_" + type + ", id=" + id + " success!");
					return true;
				} else {
					log.info("down type=index_" + type + ", id=" + id + " failed!");
				}
			} else {
				log.info("down type=" + type + ", id=" + id + " failed!");
			}
			return false;
		} catch (Exception e) {
			log.error("down type=" + type + ", id=" + id + " index error!", e);
			return false;
		}
	}

	private boolean incrementalUpdate(DownloadServiceImpl dsi, DataprocessServiceImpl dps,
	        String action, String type, String id) {
		try {
			Long lid = Long.valueOf(id);
			if (dsi.updDataById(type, lid)) {
				log.info("update type=" + type + ", id=" + id + " download success!");
				if (dps.updDataById(type, lid)) {
					log.info("update type=index_" + type + ", id=" + id + " dataprocess success!");
					return true;
				} else {
					log.info("update type=index_" + type + ", id=" + id + " dataprocess failed!");
				}
			} else {
				log.info("update type=" + type + ", id=" + id + " download failed!");
			}
			return false;
		} catch (Exception e) {
			log.error("update type=" + type + ", id=" + id + " index error!", e);
			return false;
		}
	}

	private boolean incrementalDelete(DownloadServiceImpl dsi, DataprocessServiceImpl dps,
	        String action, String type, String id) {
		try {
		    Long lid = Long.valueOf(id);
			if (dsi.delDataById(type, lid)) {
				if (dps.delDataById(type, lid)) {
					return true;
				} else {
					log.info("delete type=index_" + type + ", id=" + id + " failed!");
				}
			} else {
				log.info("delete type=" + type + ", id=" + id + " failed!");
			}
			return false;
		} catch (Exception e) {
			log.error("delete type=" + type + ", id=" + id + " index error!", e);
			return false;
		}
	}
	
	public SummaryBean fromMqMessage(long mqid, String itemId, String action, String type) {
		SummaryBean bean = new SummaryBean();

		if (Mappings.DICTIONARY_MAP == null || Mappings.DICTIONARY_MAP.size() == 0) {
			ConnectionManager cm = null;
			Connection connToSrc = null;
			Connection connToLeso = null;
			try {
				cm = ConnectionManager.getInstance();
				connToSrc = cm.getConnectionFromMMS();
				connToLeso = cm.getConnectionFromLeso();
				SQLUtil.setDictionary(connToSrc);
				SQLUtil.setStar(connToSrc);
				SQLUtil.setRAlbumMap(connToSrc);
				SQLUtil.setCagegoryMapping(connToLeso);
			} catch (Exception e) {
				log.error(mqid+",init dictionary and star map error!", e);
				bean.setErrorMsg(mqid+",init dictionary and star map error!");
				return bean;
			} finally {
			    SQLUtil.close(connToSrc);
			    SQLUtil.close(connToLeso);
			}
		}

		DownloadServiceImpl dsi = new DownloadServiceImpl();
		DataprocessServiceImpl dps = new DataprocessServiceImpl();

		boolean incrementalResult = false;

		try {

			log.info(mqid+",get msg from mq:action=" + action + " type=" + type + " itemId=" + itemId);

			if (Constants.INDEX_LESO_EXTRAET.equals(type)) {
				incrementalResult = dps.processLesoExtraetById(Integer.parseInt(itemId), action);
				if (!incrementalResult) {
					log.info(mqid+",get connection throw exception =" + incrementalResult);
                }
			} else {
				if (Constants.MQ_ACTION_DEL.equals(action)) {
					incrementalResult = incrementalDelete(dsi, dps, action, type, itemId);
				} else if (Constants.MQ_ACTION_ADD.equals(action)) {
					incrementalResult = incrementalDown(dsi, dps, action, type, itemId);
				} else if (Constants.MQ_ACTION_MOD.equals(action)) {
					incrementalResult = incrementalUpdate(dsi, dps, action, type, itemId);
				} else {
					incrementalResult = false;
				}
			}

		} catch (Exception e) {
			log.error(mqid+",incremental localupdatefile operation error!", e);
			bean.setErrorMsg(mqid+",incremental localupdatefile operation error!");
		}

		return bean;
	}
	
	public SummaryBean fromMqMessage_leso(long mqid, String itemId, String action, String type) {
		SummaryBean bean = new SummaryBean();

		if (Mappings.DICTIONARY_MAP == null || Mappings.DICTIONARY_MAP.size() == 0) {
			ConnectionManager cm = null;
			Connection connToSrc = null;
			Connection connToLeso = null;
			try {
				cm = ConnectionManager.getInstance();
				connToSrc = cm.getConnectionFromMMS();
				connToLeso = cm.getConnectionFromLeso();
				SQLUtil.setDictionary(connToSrc);
				SQLUtil.setStar(connToSrc);
				SQLUtil.setRAlbumMap(connToSrc);
	            SQLUtil.setCagegoryMapping(connToLeso);
			} catch (Exception e) {
				log.error(mqid+",init dictionary and star map error!", e);
				bean.setErrorMsg(mqid+",init dictionary and star map error!");
				return bean;
			} finally {
			    SQLUtil.close(connToSrc);
			    SQLUtil.close(connToLeso);
			}
		}

		DownloadServiceImpl dsi = new DownloadServiceImpl();
		DataprocessServiceImpl dps = new DataprocessServiceImpl();

		boolean incrementalResult = false;

		try {

			log.info(mqid+",get msg from mq:action=" + action + " type=" + type + " itemId=" + itemId);

			if (Constants.INDEX_LESO_EXTRAET.equals(type)) {
				incrementalResult = dps.processLesoExtraetById_leso(Integer.parseInt(itemId), action);
				if (!incrementalResult) {
					log.info(mqid+",get connection throw exception =" + incrementalResult);
                }
			} else {
				if (Constants.MQ_ACTION_DEL.equals(action)) {
					incrementalResult = incrementalDelete(dsi, dps, action, type, itemId);
				} else if (Constants.MQ_ACTION_ADD.equals(action)) {
					incrementalResult = incrementalDown(dsi, dps, action, type, itemId);
				} else if (Constants.MQ_ACTION_MOD.equals(action)) {
					incrementalResult = incrementalUpdate(dsi, dps, action, type, itemId);
				} else {
					incrementalResult = false;
				}
			}

		} catch (Exception e) {
			log.error(mqid+",incremental localupdatefile operation error!", e);
			bean.setErrorMsg(mqid+",incremental localupdatefile operation error!");
		}

		return bean;
	}
	
	public void cmsimg() {
		// 处理cms_img表数据，存入cbase中，key固定值为：letv_cmsimg_0_0
		ArrayList<Map<String, Object>> cmsimgLists = new ArrayList<Map<String, Object>>();

		ConnectionManager cm = null;
		Connection connLeso = null;
		try {
			cm = ConnectionManager.getInstance();

			connLeso = cm.getConnectionFromLeso();
			cmsimgLists = SQLUtil.getCMSIMGData(connLeso);
			log.info("SQLUtil.getCMSIMGData(connLeso) cmsimgLists:" + cmsimgLists.size());
			String jsonStr = JSONObject.toJSONString(cmsimgLists);
			CacheFactory.getCache().set(cbasekeyprefix+"letv_cmsimg_0_0", jsonStr);
			log.info("SQLUtil.getCMSIMGData(connLeso) cmsimgLists set cbase.");
		} catch (Exception e) {
		    SQLUtil.close(connLeso);
		}
	}

}
